﻿using System;
using Com.Ctrip.Framework.Apollo;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace rabbitmqdemo
{
    public class ConfigurationDemo
    {

        private readonly string _defaultValue = "undefined";
        private readonly IConfiguration _config;

        public ConfigurationDemo(IConfiguration config)
        {
            this._config = config;
            var services = new ServiceCollection();
            services.AddOptions()
                .Configure<Value>(config);

            services.AddSingleton<ApolloConfigurationManager>();

            var serviceProvider = services.BuildServiceProvider();

            var optionsMonitor = serviceProvider.GetService<IOptionsMonitor<Value>>();

            optionsMonitor.OnChange(OnChanged);

            new ConfigurationManagerDemo(serviceProvider.GetService<ApolloConfigurationManager>());
        }

        public string GetConfig(string key)
        {
            var result = _config.GetValue(key, _defaultValue);

            var color = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Loading key: {0} with value: {1}", key, result);
            Console.ForegroundColor = color;

            return result;
        }

        private void OnChanged(Value value, string name)
        {
            Console.WriteLine(name + " has changed: " + JsonConvert.SerializeObject(value));
        }

        private class Value
        {
            public string Timeout { get; set; }
        }
    }
}
